JavaScript 有作用域之分而 Jest 也有其作用域,之前有使用過的 describe
及 test
也涵蓋在裡面,首先先來觀察 describe
跟 test
的執行優先順序:
這邊採用官方的範例程式碼進行觀察:
describe
數量:總體結構上是最外層的 describe
(describe outer) 作用域,內層包覆兩個 describe
(describe inner 1 | describe inner 2)test
數量共計三個,位置及上下順序分別於:
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
最後觀察其印出的成果:
describe
會比 test
早執行,且印出的順序是依序由上往下// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
當然除了 describe
、 test
之外 Jest 還提供了幾種生命週期:
beforeAll(fn, timeout)
:在該區域最一開始執行一次beforeEach(fn, timeout)
:在該區域每個測試運行前執行一次afterEach(fn, timeout)
:在該區域每個測試執行完時都執行一次afterAll(fn, timeout)
:在該區域所有測試都執行完後運行一次最後來拆解官方程式碼進行執行順序的觀察:
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
如果單獨以全域情況下來看執行順序會是:beforeAll
> beforeEach
> test
> afterEach
> afterAll
,而 beforeAll 、 afterAll 只會在最初及最後個別調用一次。
beforeEach
時全域會比區域的更早調用afterEach
時區域會比全域的更早調用今天學習到關於測試的作用域,還有他們的執行優先順序!
https://jestjs.io/docs/setup-teardown
https://jestjs.io/docs/27.x/api#beforeeachfn-timeout
https://medium.com/enjoy-life-enjoy-coding/unit-test-替測試設置分類-describe-及作用域-scoping-2c5082266ca
https://shawnlin0201.github.io/Jest.js/Jest-004-setup-teardown/
https://ithelp.ithome.com.tw/articles/10222357